package com.ruoyi.pm.task;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.service.BaseService;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.pm.domain.*;
import com.ruoyi.pm.service.*;
import com.ruoyi.pm.util.SupplierUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 智管平台消息查询定时任务
 */
@Component("portPostTask")
public class PortPostTask extends BaseService {

    @Autowired
    private IExcPortService portService;

    @Autowired
    private SupplierUtil supplierUtil;

    @Autowired
    private IExcPortHeaderService excPortHeaderService;

    @Autowired
    private IExcLogService excLogService;

    @Autowired
    private IExcPortUpdateConditionService excPortUpdateConditionService;

    @Autowired
    private IExcPortConfigService excPortConfigService;


    public void sendPost(Long portId) {

        ExcPort excPort = portService.selectExcPortById(portId);
        //初始化接口日志
        ExcLog excLog = new ExcLog();
        excLog.setPortId(portId);
        //组装请求报文
        Map<String, Object> inRequest = supplierUtil.assembleRequestBody(excPort);
        excLog.setToData(JSON.toJSONString(inRequest));
        excLog.setToTime(DateUtils.getNowDate());

        ExcPortHeader excPortHeader = new ExcPortHeader();
        excPortHeader.setPortId(excPort.getId());
        List<ExcPortHeader> excPortHeaders = excPortHeaderService.selectExcPortHeaderList(excPortHeader);
        //请求服务方
        try {
            //现在就可以走服务方接口了得到返回
            Map<String, Object> supplierResponse = supplierUtil.sendSupplierRequest(excPort, inRequest, excPortHeaders);
            excLog.setOutTime(DateUtils.getNowDate());
            //判断接口是否超时
            long finishTime = excLog.getOutTime().getTime() - excLog.getToTime().getTime();
            Long timeOut = excPort.getTimeOut();
            if(StringUtils.isNotNull(timeOut)){
                long l = timeOut * 1000;
                if(l < finishTime){
                    excLog.setErrorFlag("2");
                }
            }
            //判断返回是否错误
            excLog.setErrorFlag(checkResponse(supplierResponse, portId));
            if (StringUtils.isNotEmpty(supplierResponse)) {
                excLog.setOutData(JSON.toJSONString(supplierResponse));
            }

        } catch (Exception e) {
            //0:正常 1:接口报错 2：超时错误 3：返回错误
            excLog.setErrorFlag("1");
            logger.error(e.getMessage());
        } finally {
            excLogService.insertExcLog(excLog);
        }

    }

    public String checkResponse(Map<String, Object> supplierResponse, Long portId) {
        ExcPortUpdateCondition excPortUpdateCondition = new ExcPortUpdateCondition();
        excPortUpdateCondition.setPortId(portId);
        List<ExcPortUpdateCondition> excPortUpdateConditionList = excPortUpdateConditionService.selectExcPortUpdateConditionList(excPortUpdateCondition);
        if (StringUtils.isNotEmpty(excPortUpdateConditionList)) {
            for (ExcPortUpdateCondition portUpdateCondition : excPortUpdateConditionList) {
                String matchingValue = portUpdateCondition.getMatchingValue();
                Object outFieldO = getFieldValue(supplierResponse, portUpdateCondition.getOutFieldFormula());
                ExcPortConfig excPortConfig = excPortConfigService.selectExcPortConfigById(portUpdateCondition.getPortConfigId());
                if("null".equals(matchingValue)){
                    if(StringUtils.isNull(outFieldO) || "null".equals(outFieldO)){
                        return "3";
                    }
                    //如果是List
                    try {
                        if ("3".equals(excPortConfig.getType())) {
                            if (((List) outFieldO).size() < 1) {
                                return "3";
                            }
                        }
                    }catch (Exception e){
                        logger.error(e.getMessage());
                    }
                }
                if ("3".equals(excPortConfig.getType())) {
                    continue;
                }
                String outFieldValue = String.valueOf(outFieldO);
                //正则
                if ("1".equals(portUpdateCondition.getMatchingType())) {
                    try {
                        return outFieldValue.matches(matchingValue) ? "3":"0";
                    } catch (Exception e) {
                        throw new BusinessException("后台配置数据有误，请联系管理员处理。错误码：75530");
                    }
                }
                //比较
                if ("2".equals(portUpdateCondition.getMatchingType())) {
                    String compareFlag = portUpdateCondition.getCompareFlag();
                    switch (compareFlag) {
                        case "=":
                            return matchingValue.equals(outFieldValue) ? "3":"0";
                        case ">":
                            return outFieldValue.compareTo(matchingValue) > 0 ? "3":"0";
                        case ">=":
                            return outFieldValue.compareTo(matchingValue) >= 0 ? "3":"0";
                        case "<":
                            return outFieldValue.compareTo(matchingValue) < 0 ? "3":"0";
                        case "<>":
                            return outFieldValue.compareTo(matchingValue) != 0 ? "3":"0";
                        case "in":
                            String[] split = matchingValue.split(",");
                            return Arrays.asList(split).contains(outFieldValue) ? "3":"0";
                        case "not in":
                            String[] array = matchingValue.split(",");
                            return Arrays.asList(array).contains(outFieldValue) ? "0":"3";
                        default:
                            continue;
                    }
                }
            }
        }
        return "1";
    }

    //替换InCash中的值
    public Object getFieldValue(Map<String, Object> map, String field) {
        JSONObject jsonObject;
        try {
            jsonObject = JSON.parseObject(JSON.toJSONString(map));
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BusinessException("取值失败");
        }

        String[] as = field.split("\\.");
        for (int i = 0; i < as.length; i++) {
            if (jsonObject == null) {
                break;
            }
            if (i == as.length - 1) {
                Object v = jsonObject.get(as[i]);
                if (v == null || "".equals(v)) {
                    v = "null";
                }
                return v;
            } else {
                jsonObject = (JSONObject) jsonObject.get(as[i]);
            }
        }

        return "null";
    }


}
